﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using InspectionMAC.Config;
using InspectionMAC.Algorithm;
using LitJson;
using InspectionMAC.SystemThread;
using System.Text.RegularExpressions;

namespace InspectionMAC.Forms
{
    public partial class ProductSettingForm : Form
    {
        // 映射关系
        private readonly Dictionary<CheckBox, DefectType> checkboxMapping = new Dictionary<CheckBox, DefectType>();
        private readonly Dictionary<CheckBox, DefectType1> checkboxMappingTablet = new Dictionary<CheckBox, DefectType1>();

        // 缺陷类型名称映射
        private readonly Dictionary<DefectType, string> defectTypeNames = new Dictionary<DefectType, string>
        {
            { DefectType.空泡, "空泡" },
            { DefectType.折痕, "折痕" },
            { DefectType.破边, "破边" },
            { DefectType.批次不良, "批次不良" },
            { DefectType.压泡, "压泡" },
            { DefectType.脏污, "脏污" },
            { DefectType.铝箔不良, "铝箔不良" },
            { DefectType.脱帽, "脱帽" },
            { DefectType.混料, "混料" },
            { DefectType.头发, "头发" },
            { DefectType.漏粉, "漏粉" },
            { DefectType.多粒, "多粒" },
            { DefectType.压痕, "压痕" },
            { DefectType.网纹不良, "网纹不良" },
            { DefectType.劈叉, "劈叉" },
            { DefectType.钢印OK, "钢印OK" },
            { DefectType.钢印NG, "钢印NG" }
        };

        private readonly Dictionary<DefectType1, string> defectTypeNamesTablet = new Dictionary<DefectType1, string>
        {
            { DefectType1.空泡, "空泡" },
            { DefectType1.折痕, "折痕" },
            { DefectType1.破边, "破边" },
            { DefectType1.批次不良, "批次不良" },
            { DefectType1.压泡, "压泡" },
            { DefectType1.脏污, "脏污" },
            { DefectType1.铝箔不良, "铝箔不良" },
            { DefectType1.裂纹, "裂纹" },
            { DefectType1.混料, "混料" },
            { DefectType1.头发, "头发" },
            { DefectType1.漏粉, "漏粉" },
            { DefectType1.多粒, "多粒" },
            { DefectType1.崩缺, "崩缺" },
            { DefectType1.网纹不良, "网纹不良" },
            { DefectType1.钢印OK, "钢印OK" },
            { DefectType1.钢印NG, "钢印NG" }
        };

        // JSON 文件路径
        private string SettingsFilePath = "";

        // 当前产品类型
        private ProductType currentProductType = ProductType.Capsule;

        public ProductSettingForm()
        {
            InitializeComponent();
        }

        private void ProductSettingForm_Load(object sender, EventArgs e)
        {
            SettingsFilePath = MacTestForm.SettingsFilePath;
            // 建立 checkbox 与 DefectType 的映射
            InitializeCheckboxMapping();

            // 绑定事件处理
            foreach (var cb in checkboxMapping.Keys)
            {
                cb.CheckedChanged += CheckBox_CheckedChanged;
            }
            foreach (var cb in checkboxMappingTablet.Keys)
            {
                cb.CheckedChanged += CheckBox_CheckedChanged;
            }

            // 加载保存的设置
            LoadSettingsFromJson();

            // 更新选择状态
            UpdateSelectionStatus();

            // 默认选择胶囊
            UpdateTabVisibility();
        }

        private void InitializeCheckboxMapping()
        {
            // 胶囊缺陷类型映射
            checkboxMapping.Add(checkBox1, DefectType.空泡);
            checkboxMapping.Add(checkBox2, DefectType.折痕);
            checkboxMapping.Add(checkBox3, DefectType.破边);
            checkboxMapping.Add(checkBox4, DefectType.批次不良);
            checkboxMapping.Add(checkBox5, DefectType.压泡);
            checkboxMapping.Add(checkBox6, DefectType.脏污);
            checkboxMapping.Add(checkBox7, DefectType.铝箔不良);
            checkboxMapping.Add(checkBox8, DefectType.脱帽);
            checkboxMapping.Add(checkBox9, DefectType.混料);
            checkboxMapping.Add(checkBox10, DefectType.头发);
            checkboxMapping.Add(checkBox11, DefectType.漏粉);
            checkboxMapping.Add(checkBox12, DefectType.多粒);
            checkboxMapping.Add(checkBox13, DefectType.压痕);
            checkboxMapping.Add(checkBox14, DefectType.网纹不良);
            checkboxMapping.Add(checkBox15, DefectType.劈叉);
            checkboxMapping.Add(checkBox16, DefectType.钢印OK);
            checkboxMapping.Add(checkBox17, DefectType.钢印NG);

            // 片剂缺陷类型映射
            checkboxMappingTablet.Add(checkBox01, DefectType1.空泡);
            checkboxMappingTablet.Add(checkBox02, DefectType1.折痕);
            checkboxMappingTablet.Add(checkBox03, DefectType1.破边);
            checkboxMappingTablet.Add(checkBox04, DefectType1.批次不良);
            checkboxMappingTablet.Add(checkBox05, DefectType1.压泡);
            checkboxMappingTablet.Add(checkBox06, DefectType1.脏污);
            checkboxMappingTablet.Add(checkBox07, DefectType1.铝箔不良);
            checkboxMappingTablet.Add(checkBox08, DefectType1.裂纹);
            checkboxMappingTablet.Add(checkBox09, DefectType1.混料);
            checkboxMappingTablet.Add(checkBox010, DefectType1.头发);
            checkboxMappingTablet.Add(checkBox011, DefectType1.漏粉);
            checkboxMappingTablet.Add(checkBox012, DefectType1.多粒);
            checkboxMappingTablet.Add(checkBox013, DefectType1.崩缺);
            checkboxMappingTablet.Add(checkBox014, DefectType1.网纹不良);
            checkboxMappingTablet.Add(checkBox015, DefectType1.钢印OK);
            checkboxMappingTablet.Add(checkBox016, DefectType1.钢印NG);
        }

        private void ProductSettingForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            MacTestForm.product_Form = null;
        }

        private void CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is CheckBox cb)
            {
                // 不依赖currentProductType，直接根据复选框的映射关系处理
                if (checkboxMapping.TryGetValue(cb, out DefectType defectType))
                {
                    // 这是胶囊的复选框
                    if (cb.Checked)
                    {
                        AlgorithmModule.SelectedDefectTypes.Add((int)defectType);
                    }
                    else
                    {
                        AlgorithmModule.SelectedDefectTypes.Remove((int)defectType);
                    }
                }
                else if (checkboxMappingTablet.TryGetValue(cb, out DefectType1 defectType1))
                {
                    // 这是片剂的复选框
                    if (cb.Checked)
                    {
                        AlgorithmModule.SelectedDefectTypesTablet.Add((int)defectType1);
                    }
                    else
                    {
                        AlgorithmModule.SelectedDefectTypesTablet.Remove((int)defectType1);
                    }
                }
            }

            UpdateSelectionStatus();
        }

        private void UpdateSelectionStatus()
        {
            int count = currentProductType == ProductType.Capsule
                ? AlgorithmModule.SelectedDefectTypes.Count
                : AlgorithmModule.SelectedDefectTypesTablet.Count;
        }

        private void UpdateTabVisibility()
        {
            if (comboBox1.SelectedIndex == 0) // 胶囊
            {
                tabControl1.SelectedTab = tabPage1;
                currentProductType = ProductType.Capsule;
                AlgorithmModule.CurrentProductType = ProductType.Capsule;
                AlgorithmModule.CurrentEngine = "cap.engine";
            }
            else // 片剂
            {
                tabControl1.SelectedTab = tabPage2;
                currentProductType = ProductType.Tablet;
                AlgorithmModule.CurrentProductType = ProductType.Tablet;
                AlgorithmModule.CurrentEngine = "tab.engine";
            }
            UpdateSelectionStatus();
        }

        // 保存设置到JSON
        private void SaveSettingsToJson()
        {
            try
            {
                JsonData settings = new JsonData();

                // 读取现有配置
                if (File.Exists(SettingsFilePath))
                {
                    string existingJson = File.ReadAllText(SettingsFilePath);
                    settings = JsonMapper.ToObject(existingJson);
                }

                // 只更新产品相关的配置部分
                settings[MacTestForm.ConfigKeys.ProductName] = LocalTemplateInfoTB01.Text;
                settings[MacTestForm.ConfigKeys.ProductType] = (int)currentProductType;
                settings[MacTestForm.ConfigKeys.CameraSettings] = comboBox2.SelectedIndex + 1;

                // 保存当前计数
                settings["NGCounts"] = SingleItemInfoBuilder.NGCounts;
                settings["OKCounts"] = SingleItemInfoBuilder.OKCounts;
                settings["totalCounts"] = SingleItemInfoBuilder.totalCounts;

                // 只更新缺陷类型配置
                UpdateDefectTypesInConfig(settings);

                File.WriteAllText(SettingsFilePath, settings.ToJson());
                //MessageBox.Show("产品设置已保存!");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置时出错: {ex.Message}");
            }
        }

        private void UpdateDefectTypesInConfig(JsonData settings)
        {
            // 确保保存两个产品类型的缺陷类型，无论当前选择的是哪个
            SaveCapsuleDefectTypes(settings);
            SaveTabletDefectTypes(settings);
        }

        private void SaveCapsuleDefectTypes(JsonData settings)
        {
            JsonData selectedTypesCapsule = new JsonData();
            selectedTypesCapsule.SetJsonType(JsonType.Array);

            // 从算法模块获取胶囊缺陷类型
            foreach (var defectType in AlgorithmModule.SelectedDefectTypes)
            {
                if (defectTypeNames.TryGetValue((DefectType)defectType, out string name))
                {
                    selectedTypesCapsule.Add(name);
                }
            }
            settings[MacTestForm.ConfigKeys.SelectedDefectTypes_Capsule] = selectedTypesCapsule;
        }

        private void SaveTabletDefectTypes(JsonData settings)
        {
            JsonData selectedTypesTablet = new JsonData();
            selectedTypesTablet.SetJsonType(JsonType.Array);

            // 从算法模块获取片剂缺陷类型
            foreach (var defectType in AlgorithmModule.SelectedDefectTypesTablet)
            {
                if (defectTypeNamesTablet.TryGetValue((DefectType1)defectType, out string name))
                {
                    selectedTypesTablet.Add(name);
                }
            }
            settings[MacTestForm.ConfigKeys.SelectedDefectTypes_Tablet] = selectedTypesTablet;
        }

        // 从JSON加载设置
        private void LoadSettingsFromJson()
        {
            comboBox2.SelectedIndexChanged -= comboBox2_SelectedIndexChanged;
            try
            {
                if (File.Exists(SettingsFilePath))
                {
                    string json = File.ReadAllText(SettingsFilePath);
                    JsonData settings = JsonMapper.ToObject(json);

                    // 更新UI控件
                    LocalTemplateInfoTB01.Text = settings["ProductName"]?.ToString() ?? "默认产品";

                    // 加载产品类型
                    if (settings.Keys.Contains("ProductType"))
                    {
                        currentProductType = (ProductType)int.Parse(settings["ProductType"].ToString());
                        comboBox1.SelectedIndex = (int)currentProductType;
                        AlgorithmModule.CurrentProductType = currentProductType;
                    }

                    // 加载相机设置
                    if (settings.Keys.Contains("CameraSettings"))
                    {
                        int cameraSetting = int.Parse(settings["CameraSettings"].ToString());
                        comboBox2.SelectedIndex = cameraSetting - 1;
                    }

                    // 更新算法模块的选择
                    AlgorithmModule.SelectedDefectTypes.Clear();
                    AlgorithmModule.SelectedDefectTypesTablet.Clear();

                    // 处理胶囊选择的缺陷类型
                    if (settings.Keys.Contains("SelectedDefectTypes_Capsule"))
                    {
                        JsonData selectedTypes = settings["SelectedDefectTypes_Capsule"];
                        var reverseMapping = defectTypeNames.ToDictionary(pair => pair.Value, pair => pair.Key);

                        foreach (JsonData typeName in selectedTypes)
                        {
                            string name = typeName.ToString();
                            if (reverseMapping.TryGetValue(name, out DefectType defectType))
                            {
                                AlgorithmModule.SelectedDefectTypes.Add((int)defectType);
                            }
                        }
                    }

                    // 处理片剂选择的缺陷类型
                    if (settings.Keys.Contains("SelectedDefectTypes_Tablet"))
                    {
                        JsonData selectedTypes = settings["SelectedDefectTypes_Tablet"];
                        var reverseMapping = defectTypeNamesTablet.ToDictionary(pair => pair.Value, pair => pair.Key);

                        foreach (JsonData typeName in selectedTypes)
                        {
                            string name = typeName.ToString();
                            if (reverseMapping.TryGetValue(name, out DefectType1 defectType))
                            {
                                AlgorithmModule.SelectedDefectTypesTablet.Add((int)defectType);
                            }
                        }
                    }

                    // 更新两个产品类型的checkbox状态
                    UpdateAllCheckboxStates();

                    // 手动更新标签页可见性（放在最后）
                    UpdateTabVisibility();
                }
                else
                {
                    SetDefaultSettings();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载设置时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SetDefaultSettings();
            }

            // 更新选择状态显示
            UpdateSelectionStatus();
            comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
        }

        //更新所有checkbox状态（包括两个产品类型）
        private void UpdateAllCheckboxStates()
        {
            // 临时解除事件绑定，避免触发CheckedChanged事件
            UnsubscribeCheckboxEvents();

            // 更新胶囊checkbox状态
            foreach (var kvp in checkboxMapping)
            {
                kvp.Key.Checked = AlgorithmModule.SelectedDefectTypes.Contains((int)kvp.Value);
            }

            // 更新片剂checkbox状态
            foreach (var kvp in checkboxMappingTablet)
            {
                kvp.Key.Checked = AlgorithmModule.SelectedDefectTypesTablet.Contains((int)kvp.Value);
            }

            // 重新绑定事件
            SubscribeCheckboxEvents();
        }

        // 解除事件绑定
        private void UnsubscribeCheckboxEvents()
        {
            foreach (var cb in checkboxMapping.Keys)
            {
                cb.CheckedChanged -= CheckBox_CheckedChanged;
            }
            foreach (var cb in checkboxMappingTablet.Keys)
            {
                cb.CheckedChanged -= CheckBox_CheckedChanged;
            }
        }

        // 绑定事件
        private void SubscribeCheckboxEvents()
        {
            foreach (var cb in checkboxMapping.Keys)
            {
                cb.CheckedChanged += CheckBox_CheckedChanged;
            }
            foreach (var cb in checkboxMappingTablet.Keys)
            {
                cb.CheckedChanged += CheckBox_CheckedChanged;
            }
        }

        private void SetDefaultSettings()
        {
            // 默认全选胶囊缺陷类型
            AlgorithmModule.SelectedDefectTypes = new HashSet<int>(
                Enum.GetValues(typeof(DefectType))
                    .Cast<DefectType>()
                    .Where(dt => dt != DefectType.None && dt != DefectType.未找到该缺陷类型)
                    .Select(dt => (int)dt)
            );

            // 默认全选片剂缺陷类型
            AlgorithmModule.SelectedDefectTypesTablet = new HashSet<int>(
                Enum.GetValues(typeof(DefectType1))
                    .Cast<DefectType1>()
                    .Where(dt => dt != DefectType1.None && dt != DefectType1.未找到该缺陷类型)
                    .Select(dt => (int)dt)
            );

            // 更新所有checkbox为选中状态
            foreach (var cb in checkboxMapping.Keys)
            {
                cb.Checked = true;
            }
            foreach (var cb in checkboxMappingTablet.Keys)
            {
                cb.Checked = true;
            }

            // 创建默认设置并保存
            LocalTemplateInfoTB01.Text = "DefaultProduct";
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            SaveSettingsToJson();
        }

        // 保存按钮点击事件
        public void storageBtn_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(LocalTemplateInfoTB01.Text))
            {
                MessageBox.Show("请输入产品名称!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                LocalTemplateInfoTB01.Focus();
                return;
            }

            // 检查至少选择一种缺陷类型
            int selectedCount = currentProductType == ProductType.Capsule
                ? AlgorithmModule.SelectedDefectTypes.Count
                : AlgorithmModule.SelectedDefectTypesTablet.Count;

            if (selectedCount == 0)
            {
                var result = MessageBox.Show("您没有选择任何缺陷类型，确定要保存吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                {
                    return;
                }
            }

            // 保存设置
            SaveSettingsToJson();
        }

        // 全选按钮点击事件
        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            if (currentProductType == ProductType.Capsule)
            {
                foreach (var cb in checkboxMapping.Keys)
                {
                    cb.Checked = true;
                }
            }
            else
            {
                foreach (var cb in checkboxMappingTablet.Keys)
                {
                    cb.Checked = true;
                }
            }
        }

        // 取消全选按钮点击事件
        private void btnDeselectAll_Click(object sender, EventArgs e)
        {
            if (currentProductType == ProductType.Capsule)
            {
                foreach (var cb in checkboxMapping.Keys)
                {
                    cb.Checked = false;
                }
            }
            else
            {
                foreach (var cb in checkboxMappingTablet.Keys)
                {
                    cb.Checked = false;
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateTabVisibility();
            UpdateSelectionStatus();
        }

        // 应用相机设置
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (int.TryParse(comboBox2.SelectedIndex.ToString(), out int cameraSetting))
            {
                uint userIndex = (uint)(cameraSetting + 1);
                CameraReceiveThread_01.SwitchUserSet(userIndex);
                CameraReceiveThread_02.SwitchUserSet(userIndex);
                CameraReceiveThread_03.SwitchUserSet(userIndex);
                // MessageBox.Show($"已应用相机用户集 {cameraSetting}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 新建工单按钮点击事件
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 弹出输入框让用户输入新文件名
                string newFileName = ShowInputDialog("请输入新工单文件名（不含扩展名）:", "新建工单");
                if (string.IsNullOrEmpty(newFileName))
                {
                    return; // 用户取消
                }

                // 确保文件名合法
                if (!IsValidFileName(newFileName))
                {
                    MessageBox.Show("文件名包含非法字符！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 添加.json扩展名
                newFileName += ".json";

                // 获取原始配置文件路径和目录
                string originalFilePath = MacTestForm.SettingsFilePath;
                string directory = Path.GetDirectoryName(originalFilePath);
                string newFilePath = Path.Combine(directory, newFileName);

                // 检查文件是否已存在
                if (File.Exists(newFilePath))
                {
                    MessageBox.Show("文件已存在，请换一个名字！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建新的工单配置（基于当前配置，但计数归零）
                JsonData newSettings = new JsonData();

                // 复制当前配置的基本信息
                if (File.Exists(originalFilePath))
                {
                    string existingJson = File.ReadAllText(originalFilePath);
                    JsonData currentSettings = JsonMapper.ToObject(existingJson);

                    // 复制所有配置
                    foreach (string key in currentSettings.Keys)
                    {
                        newSettings[key] = currentSettings[key];
                    }
                }
                else
                {
                    MessageBox.Show("原始配置文件不存在，无法创建新文件", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                // 新建工单时计数归零
                newSettings["NGCounts"] = 0;
                newSettings["OKCounts"] = 0;
                newSettings["totalCounts"] = 0;

                // 保存新文件
                File.WriteAllText(newFilePath, newSettings.ToJson());

                // 更新主窗体的工单配置文件路径
                MacTestForm.SettingsFilePath = newFilePath;
                SettingsFilePath = newFilePath;

                // 通知主窗体重新加载工单设置
                MacTestForm.macTestForm.ReloadProduct(newFileName);

                MessageBox.Show($"工单配置文件已新建: {newFileName}", "成功",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"新建工单配置文件时出错: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 显示输入对话框的辅助方法
        private string ShowInputDialog(string text, string caption)
        {
            Form prompt = new Form()
            {
                Width = 500,
                Height = 150,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                Text = caption,
                StartPosition = FormStartPosition.CenterParent
            };
            Label textLabel = new Label() { Left = 20, Top = 20, Text = text, Dock = DockStyle.Top };
            TextBox textBox = new TextBox() { Left = 20, Top = 50, Width = 440 };
            Button confirmation = new Button() { Text = "确定", Left = 350, Width = 100, Top = 80, DialogResult = DialogResult.OK };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;

            return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
        }

        // 检查文件名是否合法
        private bool IsValidFileName(string fileName)
        {
            return !string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
        }
    }

    // 产品类型枚举
    public enum ProductType
    {
        Capsule = 0,
        Tablet = 1
    }
}